document.addEventListener('DOMContentLoaded', function() {
  

    // 初始化测验数据 - 包含8道高等数学题目
    let quizData = JSON.parse(localStorage.getItem('mathQuiz')) || [
        {
            text: "The value of the limit lim<sub>x → 0</sub>(sinx/x) is:",
            options: ["0", "1", "∞", "does not exist"],
            correctAnswer: "B",
            explanation: "This is one of the important limits, and when x approaches 0, the limit value of sinx/x is 1."
        },
        {
            text: "The derivative of the function f (x)=x ³ at x=0 is:",
            options: ["3", "-3", "0", "∞"],
            correctAnswer: "C",
            explanation: "f'(x) = 3x²， When x=0, f'(0) = 0。"
        },
        {
            text: "The result of the indefinite integral ∫ (1/x) dx is:",
            options: ["ln|x| + C", "1/x² + C", "x + C", "e<sup>x</sup> + C"],
            correctAnswer: "A",
            explanation: "This is one of the basic integral formulas, ∫ (1/x) dx=ln | x |+C."
        },
        {
            text: "Which of the following functions satisfies the condition of Rolle's theorem on the interval [0,1]?",
            options: ["f(x) = |x - 0.5|", "f(x) = x(1 - x)", "f(x) = 1/x", "F (x)=⌊ x ⌋ (rounding function)"],
            correctAnswer: "B",
            explanation: "The Raoul theorem requires functions to be continuous in closed intervals, differentiable in open intervals, and have equal endpoint values. Only f (x)=x (1-x) satisfies all conditions."
        },
        {
            text: "The general solution of the differential equation y'' + y = 0 is:",
            options: [
                "y = C<sub>1</sub>e<sup>x</sup> + C<sub>2</sub>e<sup>-x</sup>",
                "y = C<sub>1</sub>cosx + C<sub>2</sub>sinx",
                "y = (C<sub>1</sub> + C<sub>2</sub>x)e<sup>x</sup>",
                "y = C<sub>1</sub>e<sup>x</sup> + C<sub>2</sub>"
            ],
            correctAnswer: "B",
            explanation: "This is a second-order homogeneous linear differential equation with constant coefficients. The characteristic equation is r ²+1=0, and the solution is r=± i. Therefore, the general solution is y=C ₁ cosx+C ₂ sinx."
        },
        {
            text: "The first three terms of the Taylor expansion of function f (x)=e<sup>x</sup>at x=0 are:",
            options: [
                "1 + x + x²/2",
                "1 - x + x²/2",
                "1 + x - x²/2",
                "1 - x - x²/2"
            ],
            correctAnswer: "A",
            explanation: "The Taylor expansion of e<sup>x</sup>at x=0 is: e<sup>x</sup>=1+x+x ²/2!  + x³/3!  + . .."
        },
        {
            text: "The inflection point of curve y=x ³ -3x ²+2 is:",
            options: [
                "(0, 2)",
                "(1, 0)",
                "(2, -2)",
                "There is no turning point"
            ],
            correctAnswer: "B",
            explanation: "Find the second-order derivative y''=6x-6, Make y''=0 equals x=1. When x<1, y''When<0, x>1, y''>0, so (1,0) is the inflection point."
        },
        {
            text: "The sum of the series ∑<sub>n=1</sub><sup>∞</sup>(1/n ²) is:",
            options: [
                "π²/6",
                "∞",
                "1",
                "π/4"
            ],
            correctAnswer: "A",
            explanation: "This is the famous Basel problem, where Euler proved that ∑ (1/n ²)=π ²/6."
        }
    ];
    
    // DOM元素
    const quizQuestionsContainer = document.getElementById('quiz-questions');
    const addQuestionBtn = document.getElementById('add-question-btn');
    const saveQuizBtn = document.getElementById('save-quiz-btn');
    const previewQuizBtn = document.getElementById('preview-quiz-btn');
    const questionModal = document.getElementById('question-modal');
    const closeModalBtn = document.querySelector('.close-modal');
    const cancelModalBtn = document.querySelector('.btn-cancel');
    const questionForm = document.getElementById('question-form');
    const modalTitle = document.getElementById('modal-title');
    const questionIndexInput = document.getElementById('question-index');
    
    // 加载测验题目
    loadQuizQuestions();
    
    // 事件监听器
    addQuestionBtn.addEventListener('click', openAddQuestionModal);
    closeModalBtn.addEventListener('click', closeQuestionModal);
    cancelModalBtn.addEventListener('click', closeQuestionModal);
    saveQuizBtn.addEventListener('click', saveQuiz);
    previewQuizBtn.addEventListener('click', previewQuiz);
    questionForm.addEventListener('submit', handleQuestionSubmit);
    
    // 加载测验题目
    function loadQuizQuestions() {
        quizQuestionsContainer.innerHTML = '';
        
        if (quizData.length === 0) {
            quizQuestionsContainer.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-book-open"></i>
                    <p>There are no quiz questions yet, please add them</p>
                </div>
            `;
            return;
        }
        
        quizData.forEach((question, index) => {
            const questionCard = createQuestionCard(question, index);
            quizQuestionsContainer.appendChild(questionCard);
        });
    }
    
    // 创建题目卡片
    function createQuestionCard(question, index) {
        const card = document.createElement('div');
        card.className = 'question-card';
        card.dataset.index = index;
        
        const optionsHTML = question.options.map((option, i) => {
            const letter = String.fromCharCode(65 + i);
            const isCorrect = letter === question.correctAnswer;
            return `
                <div class="option-item">
                    <span class="option-letter ${isCorrect ? 'correct-option' : ''}">${letter}.</span>
                    <span class="option-content">${option}</span>
                </div>
            `;
        }).join('');
        
        card.innerHTML = `
            <div class="question-header">
                <span class="question-number">Question ${index + 1}</span>
                <div class="question-actions">
                    <div class="btn-icon btn-edit" onclick="editQuestion(${index})">
                        <i class="fas fa-edit"></i>
                    </div>
                    <div class="btn-icon btn-delete" onclick="deleteQuestion(${index})">
                        <i class="fas fa-trash"></i>
                    </div>
                </div>
            </div>
            <div class="question-content">
                ${question.text}
            </div>
            <div class="question-options">
                ${optionsHTML}
            </div>
            ${question.explanation ? `
                <div class="question-explanation">
                    <strong>Analysis:</strong>${question.explanation}
                </div>
            ` : ''}
        `;
        
        return card;
    }
    
    // 打开添加题目模态框
    function openAddQuestionModal() {
        modalTitle.textContent = 'Add new topic';
        questionIndexInput.value = -1;
        questionForm.reset();
        questionModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    }
    
    // 关闭题目模态框
    function closeQuestionModal() {
        questionModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }
    
    // 编辑题目
    window.editQuestion = function(index) {
        const question = quizData[index];
        modalTitle.textContent = 'Edit title';
        questionIndexInput.value = index;
        
        document.getElementById('question-text').value = question.text;
        document.getElementById('option-a').value = question.options[0];
        document.getElementById('option-b').value = question.options[1];
        document.getElementById('option-c').value = question.options[2];
        document.getElementById('option-d').value = question.options[3];
        document.querySelector(`input[name="correct-option"][value="${question.correctAnswer}"]`).checked = true;
        document.getElementById('question-explanation').value = question.explanation || '';
        
        questionModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    };
    
    // 删除题目
    window.deleteQuestion = function(index) {
        if (confirm('Are you sure you want to delete this question?')) {
            quizData.splice(index, 1);
            loadQuizQuestions();
        }
    };
    
    // 处理题目提交
    function handleQuestionSubmit(e) {
        e.preventDefault();
        
        const questionText = document.getElementById('question-text').value;
        const optionA = document.getElementById('option-a').value;
        const optionB = document.getElementById('option-b').value;
        const optionC = document.getElementById('option-c').value;
        const optionD = document.getElementById('option-d').value;
        const correctAnswer = document.querySelector('input[name="correct-option"]:checked').value;
        const explanation = document.getElementById('question-explanation').value;
        const questionIndex = parseInt(questionIndexInput.value);
        
        const newQuestion = {
            text: questionText,
            options: [optionA, optionB, optionC, optionD],
            correctAnswer: correctAnswer,
            explanation: explanation
        };
        
        if (questionIndex === -1) {
            // 添加新题目
            quizData.push(newQuestion);
        } else {
            // 更新现有题目
            quizData[questionIndex] = newQuestion;
        }
        
        closeQuestionModal();
        loadQuizQuestions();
    }
    
    // 保存测验
    function saveQuiz() {
        localStorage.setItem('mathQuiz', JSON.stringify(quizData));
        alert('The test has been saved!');
    }
    
    // 预览测验
    function previewQuiz() {
        if (quizData.length === 0) {
            alert('Please add the test questions first!');
            return;
        }
        
        localStorage.setItem('previewMode', 'true');
        localStorage.setItem('previewQuiz', JSON.stringify(quizData));
        window.open('techexam.html', '_blank');
    }
});